package org.example.test.service.impl;


import org.example.test.dal.entity.Cart;
import org.example.test.dal.entity.User;
import org.example.test.dal.mapper.CartMapper;
import org.example.test.dal.mapper.UserMapper;
import org.example.test.request.UserRequest;
import org.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CartMapper cartMapper;

    @Override
    public void register(UserRequest userRequest) {

        User user = new User();
        user.setUsername(userRequest.getUsername());
        user.setEmail(userRequest.getEmail());
        user.setRole(userRequest.getRole());
        user.setPassword(userRequest.getPassword());

        userMapper.insert(user); // 插入用户信息

        Long userId = user.getId(); // 获取插入记录后生成的ID

        if (userId != null) { // 确保获取到了用户ID
            Cart cart = new Cart();
            cart.setUserId(userId);
            cartMapper.insert(cart); // 为该用户创建一个购物车
        }
    }

    @Override
    public void login(String email, String password) {
        User user = userMapper.findByEmailAndPassword(email, password);
        if (user == null) {
            throw new RuntimeException("User not found or incorrect password");
        }
    }

    @Override
    public void editAddress(Long userName, String address) {
        User user = userMapper.selectByUserName(userName);
        userMapper.editAddressByUserId(user.getId(), address);
    }
}
